package com.xiaomaoguai.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;

/**
 * @fileName: FirstChannelHandler.java
 * @author: WeiHui
 * @date: 2018/9/30 16:56
 * @version: v1.0.0
 * @since JDK 1.8
 */
public class FirstChannelHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf byteBuf = (ByteBuf) msg;

		String content = byteBuf.toString(Charset.forName("UTF-8"));
		System.out.println("content = " + content);

		ByteBuf out = getByteBuf(ctx);
		ctx.channel().writeAndFlush(out);
	}

	private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
		ByteBuf buffer = ctx.alloc().buffer();
		byte[] bytes = "你好啊，欢迎关注我的博客".getBytes(Charset.forName("UTF-8"));
		buffer.writeBytes(bytes);
		return buffer;
	}
}
